package com.wei.czz.framework.blog.helper;

import com.wei.czz.common.constant.RedisConstant;
import com.wei.czz.common.dto.common.NameValue;
import com.wei.czz.common.utils.SecurityUtils;
import com.wei.czz.framework.blog.entity.SpaceEntity;
import com.wei.czz.framework.blog.service.SpaceService;
import com.wei.czz.framework.common.handler.redis.RedisHashHandler;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by IntelliJ IDEA.
 *
 * @author wyw
 * date: 2025-02-19 22:12:30
 * className: SpaceHelper
 * version: 1.0
 * description:
 */
@Component
@AllArgsConstructor
public class SpaceHelper {

    private static final Logger log = LoggerFactory.getLogger(SpaceHelper.class);

    private final SpaceService spaceService;

    private final RedisHashHandler redisHashHandler;

    /**
     * 获取用户博客空间列表操作
     * @return 空间列表
     */
    public List<NameValue<String>> getSpaceList() {
        // 获取操作用户主键
        Long optUserId = SecurityUtils.getUserId();

        // 查询Redis，获取用户所有空间信息
        List<SpaceEntity> spaceList = redisHashHandler.values(optUserId + RedisConstant.SPLIT + RedisConstant.SPACE_MAP);
        log.info("从缓存获取用户博客空间列表结果：{}", spaceList);
        if (spaceList.isEmpty()) {
            /*
                获取用户博客空间列表
             */
            spaceList = spaceService.getSpaceList(optUserId);
        }
        // 列表映射返回
        return spaceList.stream()
                .sorted(Comparator.comparing(SpaceEntity::getSort))
                .map(space -> new NameValue<>(space.getName(), space.getSpaceId().toString()))
                .collect(Collectors.toList());
    }
}
